package org.example;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.sql.Array;
import java.util.ArrayList;

/**
 * @Author: ChromeChen
 * @Description:
 * @Date: Created in 18:40 2024/1/13 0013
 * @Modified By:
 */
@Slf4j
public class BioDemo01 {

    public static class BioServer {
        public static void main(String[] args) throws IOException {
            ByteBuffer buffer = ByteBuffer.allocate(16);
            // 1. 创建服务器
            ServerSocketChannel ssc = ServerSocketChannel.open();

            // 2. 绑定监听端口
            ssc.bind(new InetSocketAddress(8080));

            // 3. 用一个数组保存连接
            ArrayList<SocketChannel> channels = new ArrayList<>();

            while (true) {
                // 4. accept 建立与客户端连接，SocketChannel 用来与客户端之间通信
                log.info("connecting...");
                // 这个是阻塞方法
                SocketChannel sc = ssc.accept();
                log.info("connected... {}", sc);

                channels.add(sc);

                for (SocketChannel channel : channels) {
                    // 5. 接收客户端发送的数据
                    log.info("before read... {}", channel);
                    // 读取数据，这个方法是阻塞的
                    channel.read(buffer);

                    buffer.flip();
                    log.info("read content: {}", buffer.toString());

                    buffer.clear();
                    log.info("after read... {}", channel);
                }
            }
        }
    }

    public static class BioClient {
        public static void main(String[] args) throws IOException {
            SocketChannel sc = SocketChannel.open();
            sc.connect(new InetSocketAddress("127.0.0.1", 8080));
            log.info("client waiting... ");
            System.in.read();
        }
    }
}
